package handler

import (
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"path/filepath"
	"time"
	"zg5/videos/api-gateway/internal/request"
	"zg5/videos/common/global"
	"zg5/videos/common/pkg"
	"zg5/videos/common/proto/videos"
)

func AddVideo(c *gin.Context) {
	var req request.AddVideoReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  err.Error(),
			"Data": nil,
		})
		return
	}

	// 单文件
	file, _ := c.FormFile("file")
	log.Println(file.Filename)

	if file.Size > 150*1024*1024 {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "文件大小不能超过150MB",
			"Data": nil,
		})
		return
	}

	ext := filepath.Ext(file.Filename)
	//if ext != ".mp4" {
	//	c.JSON(http.StatusOK, gin.H{
	//		"code": 500,
	//		"msg":  "文件类型错误",
	//		"Data": nil,
	//	})
	//	return
	//}

	filename := time.Now().Format("20060102150405") + ext

	dst := "./static/image/" + filename
	// 上传文件至指定的完整文件路径
	err := c.SaveUploadedFile(file, dst)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "文件上传失败",
			"Data": nil,
		})
		return
	}

	upload, err := pkg.Upload(filename, dst)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "文件上传失败",
			"Data": nil,
		})
		return
	}

	_, err = global.VideosGrpc.AddVideo(c, &videos.AddVideoRequest{
		UserId:       uint64(req.UserId),
		Name:         filename,
		Format:       ext,
		Size:         uint64(file.Size),
		TypesId:      uint64(req.TypesId),
		UploadMethod: uint64(req.UploadMethod),
		Addr:         uint64(req.Addr),
		Recommend:    uint64(req.Recommend),
	})
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  err.Error(),
			"Data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "success",
		"Data": upload,
	})
}

func VideoList(c *gin.Context) {
	var req request.VideoListReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  err.Error(),
			"Data": nil,
		})
		return
	}
	list, err := global.VideosGrpc.VideoList(c, &videos.VideoListRequest{
		Page:      uint64(req.Page),
		Size:      uint64(req.Size),
		Status:    uint64(req.Status),
		Recommend: uint64(req.Recommend),
		UserId:    uint64(req.UserId),
	})
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  err.Error(),
			"Data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "success",
		"Data": list,
	})
}
